import {action, Service} from "adajs";

class ListsService extends Service {
    defaultData() {
        return {
            url: "",
            list: [],
            isLoading: true,
            isEnd: false,
            isError: false,
            pageSize: 10,
            page: 0,
            parameter: {},
            type: null,
            method: "post",
            option: {}
        };
    }

    onupdate(current, info) {
        Object.assign(current, info);
        current.isError = false;
        current.page = 0;
        current.isLoading = true;
        current.list = [];
        current.isEnd = false;
    }

    @action("showLoading")
    showLoading(current) {
        current.isLoading = true;
        current.isEnd = true;
    }

    gotoPage(current, page) {
        return this.context.request[current.method](current.url, Object.assign({
            page,
            pageSize: current.pageSize
        }, current.parameter)).then(({data}) => {
            if (data) {
                if (Array.isArray(data)) {
                    data.rows = data;
                }
                current.isError = false;
                current.page = page;
                current.isLoading = false;
                current.list = [...current.list, ...data.rows];
                current.isEnd = data.rows.length < current.pageSize;
            } else {
                current.isError = true;
            }
        }, () => {
            current.isError = true;
        });
    }

    @action("nextPage")
    nextPage(current) {
        return this.gotoPage(current, current.page + 1);
    }

    @action("retry")
    retry(current) {
        return this.gotoPage(current, current.page);
    }
}

export default ListsService;